package com.aiyige.page.my.customer.fragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventCustomerChanged;
import com.aiyige.base.eventbus.EventCustomerFollowupAddSuccess;
import com.aiyige.model.CustomerRequestModel;
import com.aiyige.model.request.GetCustomerFollowUpListRequest;
import com.aiyige.model.response.CustomerFollowUpListResponse;
import com.aiyige.page.my.customer.adapter.CustomerBaseDataListAdapter;
import com.aiyige.page.my.customer.model.CustomerEntity;
import com.aiyige.page.my.customer.model.CustomerFollowupEntity;
import com.aiyige.page.my.customer.model.CustomerType;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.launcher.ARouter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * 客户基本资料
 * Created by xiachao on 2018/3/28.
 */

public class CustomerBaseDataPage extends BaseFragment implements CommonDataView.RetrofitStub {
    View rootView;

    CommonDataView cdv;
    Unbinder unbinder;
    View headerView;
    CustomerBaseDataListAdapter adapter;


    CustomerEntity customerEntity;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_client_type_value)
    TextView tvClientTypeValue;
    @BindView(R.id.tv_phone_value)
    TextView tvPhoneValue;
    @BindView(R.id.tv_customer_from_value)
    TextView tvCustomerFromValue;
    @BindView(R.id.tv_transaction_value)
    TextView tvTransactionValue;
    @BindView(R.id.tv_last_follow_up_value)
    TextView tvLastFollowUpValue;
    @BindView(R.id.tv_next_follow_up_value)
    TextView tvNextFollowUpValue;
    @BindView(R.id.tv_remark_value)
    TextView tvRemarkValue;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.page_customer_base_data, container, false);
        cdv = (CommonDataView) rootView.findViewById(R.id.cdv);
        return rootView;
    }

    public static CustomerBaseDataPage newInstance() {
        CustomerBaseDataPage fragment = new CustomerBaseDataPage();
        return fragment;
    }


    @Override
    protected void initData() {
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.headerview_customer_detail, null);
        unbinder = ButterKnife.bind(this, headerView);
        headerView.findViewById(R.id.iv_edit_profile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build(ARouterConfig.CustomerEditBaseDataPage)
                        .withParcelable("customer", customerEntity).navigation(getActivity(), 1);
            }
        });
        adapter = new CustomerBaseDataListAdapter();
        cdv.config(adapter, this);
        adapter.setHeaderFooterEmpty(true, false);
        adapter.addHeaderView(headerView);
//        adapter.setNewData(Arrays.asList(new CustomerFollowupEntity(), new CustomerFollowupEntity(), new CustomerFollowUpEntity(), new CustomerFollowUpEntity(), new CustomerFollowUpEntity(), new CustomerFollowUpEntity(), new CustomerFollowUpEntity(), new CustomerFollowUpEntity(), new CustomerFollowUpEntity(), new CustomerFollowUpEntity()));
        cdv.hideCoverLayout();
        cdv.clearRequestState();
        adapter.loadMoreComplete();
        cdv.requestData();
        fillViews();
        setAutoRegisterEventBus(true);
    }

    /**
     * 用户编辑后刷新页面
     *
     * @param eventCustomerChanged
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventCustomerChanged(EventCustomerChanged eventCustomerChanged) {
        CustomerRequestModel customerRequestModel = eventCustomerChanged.getCustomerRequestModel();
        if (customerRequestModel != null) {
            customerEntity.setName(customerRequestModel.getName());
            customerEntity.setCustomerType(customerRequestModel.getType());
            customerEntity.setCustomerFrom(customerRequestModel.getFromChannel());
            customerEntity.setPhone(customerRequestModel.getMobile());
            customerEntity.setRemark(customerRequestModel.getRemark());
            customerEntity.setSex(customerRequestModel.getSex());
            customerEntity.setFollowupTime(customerRequestModel.getFollowupTime());
            customerEntity.setNextFollowupTime(customerRequestModel.getNextFollowupTime());
            fillViews();
        }
    }

    /**
     * 用户编辑后刷新页面
     *
     * @param eventCustomerFollowupAddSuccess
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventCustomerFollowupAddSuccess(EventCustomerFollowupAddSuccess eventCustomerFollowupAddSuccess) {
        CustomerFollowupEntity followupEntity = eventCustomerFollowupAddSuccess.getCustomerFollowupEntity();
        if (followupEntity != null) {
            adapter.addData(0, followupEntity);
            tvNextFollowUpValue.setText(followupEntity.getNextFollowupTime() > 1000 ? TimeUtils.dateToYYYYMMDD(Long.parseLong(customerEntity.getNextFollowupTime())) : "");
            customerEntity.setFollowupTime(followupEntity.getNearestFollowupTime() + "");
            customerEntity.setNextFollowupTime(followupEntity.getNearestNextFollowupTime() + "");
            fillViews();
        }
    }


    private void fillViews() {
        if (customerEntity == null) {
            return;
        }
        GlideUtil.with(getActivity()).small().loadAvatar(customerEntity.getAvatar()).into(ivHead);
        tvName.setText(customerEntity.getName());
        if (TextUtils.isEmpty(customerEntity.getSex())) {
            tvName.setCompoundDrawables(null, null, null, null);
        } else {
            Drawable drawableNormal = getResources().getDrawable(customerEntity.islady() ? R.drawable.personal_girl : R.drawable.personal_boy);
            drawableNormal.setBounds(0, 0, drawableNormal.getIntrinsicWidth(), drawableNormal.getIntrinsicHeight());
            tvName.setCompoundDrawables(null, null, drawableNormal, null);
        }

        tvClientTypeValue.setText(CustomerType.getName(customerEntity.getCustomerType()));
        tvPhoneValue.setText(customerEntity.getPhone());
        tvCustomerFromValue.setText(customerEntity.getCustomerFrom());
        tvTransactionValue.setText(StringUtils.priceFormat(customerEntity.getTotalTransactionPrice())
                + getActivity().getString(R.string.yuan) + "/"
                + customerEntity.getTotalTransactionOrderCount() + getActivity().getString(R.string.bill));
        tvLastFollowUpValue.setText(Long.parseLong(customerEntity.getFollowupTime()) > 1000 ? TimeUtils.dateToYYYYMMDD(Long.parseLong(customerEntity.getFollowupTime())) : "");
        tvNextFollowUpValue.setText(Long.parseLong(customerEntity.getNextFollowupTime()) > 1000 ? TimeUtils.dateToYYYYMMDD(Long.parseLong(customerEntity.getNextFollowupTime())) : "");
        if (!TextUtils.isEmpty(customerEntity.getRemark())) {
            tvRemarkValue.setVisibility(View.VISIBLE);
            tvRemarkValue.setText(customerEntity.getRemark());
        }


    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return GetCustomerFollowUpListRequest.newBuilder().customerId(customerEntity.getId()).pageNum(currentPage + "").build();
//        return GetCustomerFollowUpListRequest.newBuilder().customerId("402861816266f790016266f8b50f0000").pageNum(currentPage+"").build();
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        String respJsonTest = respJson;
        Log.v("XiachaoTest", respJsonTest);
        try {
            CustomerFollowUpListResponse homeResponse = JsonUtil.toObject(respJson, CustomerFollowUpListResponse.class);
            if (ListUtil.isEmpty(homeResponse.getContent())) {
                resultList.addAll(homeResponse.getContent());
                return new CommonDataView.HandleResult(homeResponse.isLast());
            } else {
                List<CustomerFollowupEntity> responseList = homeResponse.getContent();
                resultList.addAll(responseList);
                return new CommonDataView.HandleResult(homeResponse.isLast());
            }

        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    @OnClick({R.id.tv_add_follow_up, R.id.rl_add_follow_up})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_add_follow_up:
            case R.id.rl_add_follow_up:
                ARouter.getInstance().build(ARouterConfig.AddFollowUpPage).withParcelable("customer", customerEntity).navigation();
                break;
        }
    }

    public void setCustomerEntity(CustomerEntity customerEntity) {
        this.customerEntity = customerEntity;

    }

}
